import './index.css';
import { useState, useEffect } from 'react';
import axios from 'axios';
import FormPopup from '../../components/popups/formPopup/formPopup';
import emitter from '../../utils/event';
function PrizeList() {
    const [prizeListAll, setPrizeListAll] = useState([])
    const [otherDisabled, setOtherDisabled] = useState(false)
    const checkedLength = () => {
        return prizeListAll.findIndex((item) => item.checked === false);
    }
    useEffect(() => {
        const length = prizeListAll.findIndex((item) => item.checked === false);
        if (length >= 8) {
            setOtherDisabled(true)
        } else {
            setOtherDisabled(false)
        }
        return () => {

        }
    }, [prizeListAll])
    useEffect(() => {
        axios.get('/V1/admin/prize/pool')
            .then((res) => {
                if (res.data.code === 200) {
                    setPrizeListAll(res.data.data)
                }
            })
            .catch((err) => {
                console.log(err)
            })
        return () => {

        }
    }, [])
    const onCheckBoxChanged_All = (index, event) => {
        const firstNoCheckedIndex = checkedLength();
        let prize = prizeListAll[index];
        prize.checked = !prize.checked;
        if (prize.checked === true) {
            prize.probability = 0;
            setPrizeListAll([
                ...(prizeListAll.slice(0, firstNoCheckedIndex)),
                prize,
                ...(prizeListAll.slice(firstNoCheckedIndex, index)),
                ...(prizeListAll.slice(index + 1, prizeListAll.length))
            ])
        }
        else {
            setPrizeListAll([
                ...(prizeListAll.slice(0, index)),
                ...(prizeListAll.slice(index + 1, firstNoCheckedIndex)),
                prize,
                ...(prizeListAll.slice(firstNoCheckedIndex, prizeListAll.length))
            ])
        }
    }
    const onClickDown_All = (index) => {
        if (prizeListAll[index + 1] && prizeListAll[index + 1].checked === true) {
            setPrizeListAll([
                ...(prizeListAll.slice(0, index)),
                prizeListAll[index + 1],
                prizeListAll[index],
                ...(prizeListAll.slice(index + 2, prizeListAll.length))
            ])
        }
    }
    const onClickUp_All = (index) => {
        if (prizeListAll[index - 1] && prizeListAll[index].checked === true) {
            setPrizeListAll([
                ...(prizeListAll.slice(0, index - 1)),
                prizeListAll[index],
                prizeListAll[index - 1],
                ...(prizeListAll.slice(index + 1, prizeListAll.length))
            ])
        }
    }
    const onClickDelete_All = (index) => {
        setPrizeListAll([
            ...(prizeListAll.slice(0, index)),
            ...(prizeListAll.slice(index + 1, prizeListAll.length))
        ])
    }
    const onClickEdit = (index) => {
        emitter.emit('openFormPopup', "编辑奖品", prizeListAll[index], index)
    }
    const onChangeProbability = (index, event) => {
        let prize = prizeListAll[index];
        const value = Number(event.target.value);
        let probability = 0;
        prizeListAll.forEach((item, idx) => {
            if (item.checked && idx !== index) {
                probability += item.probability;
            }
        });
        if (probability + value >= 1) {
            prize.probability = 1 - probability;
        } else {
            prize.probability = value;
        }
        event.target.value = prize.probability;
        setPrizeListAll([
            ...prizeListAll.slice(0, index),
            prize,
            ...prizeListAll.slice(index + 1, prizeListAll.length)
        ])
    }
    const onClickSave = () => {
        const config = {
            method: 'post',
            url: '/V1/prize/pool/all',
            headers: {
                'Content-Type': 'application/json'
            },
            data: { data: prizeListAll }
        };
        axios(config)
            .then(function (response) {
                if(response.data.code===200){
                    alert("保存成功")
                }
            })
            .catch(function (error) {
                console.log(error);
            });
    }
    const onClickAdd = () => {
        emitter.emit('openFormPopup', "添加奖品")
    }
    const handlePeizeSave = (prize, index) => {
        if (index === -1) {
            setPrizeListAll([
                ...prizeListAll,
                prize
            ])
        } else {
            setPrizeListAll([
                ...prizeListAll.slice(0, index),
                prize,
                ...prizeListAll.slice(index + 1, prizeListAll.length)
            ])
        }
    }
    return (
        <div>
            <div>
                <div className="prize-list-all--header">
                    <h1>
                        奖池管理
                    </h1>
                    <div className="prize-list-all--header__btn_group">
                        <button className="btn_group--add" onClick={onClickAdd}>添加</button>
                        <button className="btn_group--save" onClick={onClickSave}>保存</button>
                    </div>
                </div>
                <table className="prize-list-all--table">
                    <thead>
                        <tr className="prize-list-all--table__header">
                            <th width="40"></th>
                            <th width="40">序号</th>
                            <th width="150">奖品名</th>
                            <th width="100">物品类型</th>
                            <th width="50">价值</th>
                            <th width="100">图片</th>
                            <th width="80">概率</th>
                            <th width="50">移动</th>
                            <th width="50">编辑</th>
                            <th width="50">删除</th>
                        </tr>
                    </thead>
                    <tbody>
                        {
                            prizeListAll.map((item, index) => {
                                return (
                                    <tr className="prize-list-all--table__body" key={index}>
                                        <td>
                                            <input type="checkbox" checked={item.checked ? "checked" : ""} onChange={onCheckBoxChanged_All.bind(this, index,)}
                                                disabled={otherDisabled && !item.checked} />
                                        </td>
                                        <td>{index}</td>
                                        <td>{item.text}</td>
                                        <td>{item.object === "real" ? "实物" : "矿石"}</td>
                                        <td>{item.value}</td>
                                        <td>
                                            <img src={item.image} alt="" />
                                        </td>
                                        <td>
                                            <div>
                                                <input type="number"
                                                    name="" id=""
                                                    className="probability-input"
                                                    disabled={!item.checked}
                                                    onBlur={onChangeProbability.bind(this, index,)}
                                                    defaultValue={item.probability}
                                                    key={item.probability}
                                                />
                                            </div>
                                        </td>
                                        <td>
                                            <div style={{ display: item.checked ? "block" : "none" }}>
                                                <i className="iconfont icon-a-arrowdown my-icon-arrow" onClick={onClickDown_All.bind(this, index,)}></i>
                                                <i className="iconfont icon-a-arrowup my-icon-arrow" onClick={onClickUp_All.bind(this, index,)}></i>
                                            </div>
                                        </td>
                                        <td>
                                            <i className="iconfont icon-edit my-icon-edit" onClick={onClickEdit.bind(this, index,)}></i>
                                        </td>
                                        <td>
                                            <i className="iconfont icon-delete my-icon-delete" onClick={onClickDelete_All.bind(this, index,)}></i>
                                        </td>
                                    </tr>
                                )
                            })
                        }
                    </tbody>
                </table>
            </div>
            <FormPopup save={handlePeizeSave}></FormPopup>
        </div>
    );
}

export default PrizeList;
